package com.lry.util.mysql.util;

import com.mysql.cj.jdbc.ClientPreparedStatement;
import com.mysql.cj.jdbc.JdbcStatement;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ALI
 * @since 2023/2/27
 */
@Slf4j
public class DbUtil {
    public static final String LOCAL_INFILE_CMD
        = "LOAD DATA LOCAL INFILE '%s' INTO TABLE %s FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n'";

    /**
     * 构建local infile 命令
     *
     * @param tableName 表名（要将数据导入到哪个表）
     */
    public static String getLocalInfileCommand(String tableName) {
        return String.format(LOCAL_INFILE_CMD, tableName, tableName);
    }

    /**
     * 导入数据
     *
     * @param connection  数据连接对象
     * @param sql         local infile 命令
     * @param inputStream 输入留（csv的输入流）
     */
    public static void localInfileMysql8(Connection connection, String sql, InputStream inputStream) {
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            if (preparedStatement.isWrapperFor(JdbcStatement.class)) {
                ClientPreparedStatement unwrap = preparedStatement.unwrap(ClientPreparedStatement.class);
                unwrap.setLocalInfileInputStream(inputStream);
                unwrap.executeUpdate();
            } else {
                log.warn("数据库链接声明并没有实现JdbcStatement，无法完成local infile命令！");
            }
        } catch (SQLException e) {
            log.error("执行local infile命令失败！语法或版本异常", e);
            throw new RuntimeException("执行local infile命令失败！语法或版本异常" + e.getMessage(), e);
        } catch (Exception e) {
            log.error("执行local infile命令失败！", e);
            throw new RuntimeException("执行local infile命令失败！" + e.getMessage(), e);
        }
    }

    public static Connection getConnection(String url, String username, String pwd) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(url, username, pwd);
        } catch (ClassNotFoundException e) {
            log.error("链接驱动异常：没有找到com.mysql.cj.jdbc.Driver驱动", e);
            e.printStackTrace();
            throw new RuntimeException("链接驱动异常：没有找到com.mysql.cj.jdbc.Driver驱动", e);
        } catch (SQLException e) {
            log.error("链接驱动异常：" + e.getMessage(), e);
            e.printStackTrace();
            throw new RuntimeException("链接驱动异常：" + e.getMessage(), e);
        } catch (Exception e) {
            log.error("链接驱动异常：" + e.getMessage(), e);
            e.printStackTrace();
            throw new RuntimeException("链接驱动异常：" + e.getMessage(), e);
        }
    }
}
